#!/usr/bin/perl

# ./webapp-starter.pl -app MyApp -db 'dbi:Pg:dbname=sample akihito'

use strict;
use warnings;
use Getopt::Long;
use IO::File;
use HTML::Template;

my $app      = '';
my $db       = '';

my $result = GetOptions ( "app=s"       => \$app,
                          "db=s"        => \$db );

if( $app ){
    system("mkdir ./lib");
    system("mkdir ./t");

    my ($db_name,$db_user,$db_passwd) = split(' ',$db);
    my $dbclass_name = $app.'DB';

    system( qq|perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./lib -e 'make_schema_at("$dbclass_name", { relationships => 1 }, [ "$db_name","$db_user","$db_passwd"])'|);

    my $line;
    do {$line .= $_ if($_);} while( <DATA> );
#my $tt = Template->new();
#print $tt->process(\$line)."<\n";
    my $ht = HTML::Template->new(scalarref=>\$line);

    $ht->param({
                    PACKAGE      => 1,
                    APP_NAME     => $app,
               });

     _output($ht->output,"lib/$app.pm");

    $ht->param({
                    PACKAGE      => 0,
                    INDEX_CGI    => 1,
#                    DB_OBJ_NAME  => $dbclass_name,
                    DB_NAME      => $db_name   || '',
                    DB_USER      => $db_user   || '',
                    DB_PASSWD    => $db_passwd || ''
               });
     _output($ht->output,"index.cgi");

#print "$str\n";

}

sub _output{
     my $str       = shift;
     my $file      = shift;
     my $fh = new IO::File();
     $fh->open($file,'w') || die "canot open $file";
     print $fh $str;
     $fh->close(); 
     print "Create:$file\n";

}

__DATA__
<TMPL_IF INDEX_CGI>#!/usr/bin/perl

use strict;
use lib 'lib';
use <TMPL_VAR APP_NAME>;

my $webapp = <TMPL_VAR APP_NAME>->new(
                TMPL_PATH => 't/',
                PARAMS => {
                    db_name   => '<TMPL_VAR DB_NAME>',
                    db_user   => '<TMPL_VAR DB_USER>',
                    db_passwd => '<TMPL_VAR DB_PASSWD>',
                }
);

$webapp->run();

</TMPL_IF><TMPL_IF PACKAGE>package <TMPL_VAR APP_NAME>;
use base 'CGI::Application';

use strict;
use <TMPL_VAR APP_NAME>DB;

sub setup {
    my $self = shift;
    $self->start_mode('index');
    $self->mode_param('rm');
    $self->run_modes(
            'index' => 'index',
    );

    my $db_name   = $self->param('db_name');
    my $db_user   = $self->param('db_user');
    my $db_passwd = $self->param('db_passwd');

    my $appdb = <TMPL_VAR APP_NAME>DB->connect((
            $db_name,
            $db_user,
            $db_passwd,
            { AutoCommit => 0 }
        ));
    $self->param('appdb',$appdb);
}

sub teardown{
    my $self = shift;
    my $appdb = $self->param('appdb');
#    $appdb->txn_commit;
    $appdb->storage->disconnect();
}

sub index {
    my $self = shift;
    return 'index <TMPL_VAR APP_NAME>';
}

1;
</TMPL_IF>

